package top.yamhk.agent.utils;

import cn.hutool.core.io.FileUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import top.yamhk.agent.entity.dto.Felicity;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 文件读取访问工具类
 *
 * @author 庆 HongKong
 * @date 2022/02/22 22:22
 */
@Slf4j
public class FileReaderAccess {
    /**
     * doDataRead
     * fp
     *
     * @param in in
     * @return String
     * @throws IOException IOException
     */
    @SneakyThrows
    public static String doDataRead(InputStream in) {
        int len;
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        while ((len = in.read(buffer)) > 0) {
            byteArrayOutputStream.write(buffer, 0, len);
        }
        byteArrayOutputStream.close();
        log.debug("文件创建-复制-{}", len);
        return byteArrayOutputStream.toString();
    }

    public List<String> readFileFromPcFile(String fileName) {
        return FileUtil.readLines(fileName, Felicity.encode);
    }

    public List<String> readFileFromProjectFile(String fileName) {
        try (InputStream resourceAsStream = this.getClass().getResourceAsStream(fileName)) {
            final String dataString = doDataRead(resourceAsStream);
            List<String> collect = Arrays.stream(dataString.split("\n"))
                    .filter(e -> !e.contains("//"))
                    .map(e -> e.replaceAll("\\r", ""))
                    .collect(Collectors.toList());
            log.debug("{}", collect);
            return collect;
        } catch (Exception e) {
            log.error("文件读取异常-[{}]-[{}]", fileName, e.getMessage());
            return new ArrayList<>();
        }
    }

    @SneakyThrows
    public List<String> readFileFromJFile(String fileName) {
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource resource = resolver.getResource(fileName);
        //
        BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
        return reader.lines().collect(Collectors.toList());
    }
}